/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package utility;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author jay
 */
public class StringUtils {

    public StringUtils() { }
    
    public static final String SQLDATE_PATERN = "YYYY-MM-DD";
    
    public static String fmtSQLString(String value) {
        return "\'"+value+"\'";
    }
    
    public static String formatDate(Date date) {
        DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
	return dateFormat.format(date);
    }
    
    public static String formatTime24(Date date) {
        DateFormat dateFormat = new SimpleDateFormat("HH:mm");
	return dateFormat.format(date);
    }
    
    public static String formatDateTime24(Date date) {
        DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
	return dateFormat.format(date);
    }
    
    public static String formatDateCustom(Date date, String format) {
        DateFormat dateFormat = new SimpleDateFormat(format);
	return dateFormat.format(date);
    }
	
//    public static String fmtSQLDate(java.util.Date value) {
//        return "date\'"+value+"\'";
//    }
    
    public static String formatSqlDate(Date date){
        return "to_date('".concat(new SimpleDateFormat("yyyy-MM-dd").format(date)).concat("','").concat(SQLDATE_PATERN).concat("')");
    }
        
//    public static String getValueFromTextNumber(String text) {
//        final char txt[] = text.toCharArray();
//        StringBuilder sb = new StringBuilder();
//        String tmp;
//        for (int i=0; i<txt.length; i++) {
//            tmp = String.valueOf(txt[i]);
//
//            if (tmp.equals(".") || tmp.equals(",")) {
//            } else {
//                sb.append(tmp);
//            }
//        }
//        return sb.toString();
//    }
    
    public static String formatNumber(BigDecimal value) {
        NumberFormat numberFormatter= NumberFormat.getInstance();
        String formatOut=numberFormatter.format(value);
        return formatOut;
    }
    
//    public static BigDecimal textToNumber(String value) {
//        NumberFormat format = NumberFormat.getCurrencyInstance( new Locale("in","ID"));
//        Number number = null;
//        try {
//            number = format.parse(value);
//        } catch (ParseException ex) {
//            Logger.getLogger(StringUtils.class.getName()).log(Level.SEVERE, null, ex);
//        }
//        BigDecimal formatOut = BigDecimal.valueOf(number.doubleValue());
//        
//        return formatOut;
//    }    
    
    public static int textToInt(String value) {
        NumberFormat format = NumberFormat.getInstance(new Locale("in","ID"));
        Number number = null;
        try {
            number = format.parse(value);
        } catch (ParseException ex) {
            Logger.getLogger(StringUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return number.intValue();
    }    
    
    public static String terbilang(String angka) {
        int length = angka.length();
        if (length <= 6) {
        String[] bil = new String[]
        {"","Satu","Dua","Tiga","Empat","Lima",

        "Enam","Tujuh","Delapan","Sembilan","Sepuluh","Sebelas"};

        int x = Integer.valueOf(angka);

        if (x <= 0) {return "";}
        else if (x < 12) {
            return bil[(int)x] + " ";
        } else if (x < 20) {
            return terbilang(String.valueOf(x-10)) + "Belas ";
        } else if (x < 100) {
            return terbilang(String.valueOf(x/10)) + "Puluh " +  terbilang(String.valueOf(x%10));
        } else if (x < 200) {
            return "Seratus " + terbilang(String.valueOf(x-100));
        } else if (x < 1000) {
            return terbilang(String.valueOf(x/100)) + "Ratus " + terbilang(String.valueOf(x%100));
        } else if (x < 2000) {
            return "Seribu " + terbilang(String.valueOf(x-1000));
        } else {
            return terbilang(String.valueOf(x/1000)) + "Ribu " +  terbilang(String.valueOf(x%1000));
        }
        } else {
            int m = length % 3;
            if (m == 0) {m = 3;}
            String s1 = angka.substring(0,m);
            String s2 = angka.substring(m,length);

            String[] bil = new String[]{"","Juta","Milyar","Trilyun","Kuadriliun", "Kuintiliun","Heksiliun"};
            int index = 0;

            if (length <= 9) {index = 1;}
            else if (length <= 12) {index = 2;}
            else if (length <= 15) {index = 3;}
            else if (length <= 18) {index = 4;}
            else if (length <= 21) {index = 5;}
            else if (length <= 24) {index = 6;}
            else {return "zzzzz... capek hitungnya";}

            if (Integer.valueOf(s1) <= 0) {
                return terbilang(s2);
            } else {
                return terbilang(s1) + bil[index] + " " + terbilang(s2);
            }
          }
        }     
    
    public static String terbilangDecimal(BigDecimal value){

        BigDecimal nilai = value.setScale(2, RoundingMode.UP);
        String rs;
        Character simbol = new Character('.');
        if (String.valueOf(nilai).indexOf(simbol.toString())>0){
            BigDecimal decimal = nilai.subtract(new BigDecimal(nilai.intValue()));
            if (decimal.multiply(new BigDecimal(100)).compareTo(new BigDecimal(BigInteger.ZERO))>0){
                int angkaDecimal  = (decimal.multiply(new BigDecimal(100))).intValue();    
                
                rs = terbilang(String.valueOf(nilai.intValue())).concat("Koma ").concat(terbilang(String.valueOf(angkaDecimal)));
            }
            else {
                rs = terbilang(String.valueOf(nilai.intValue()));
            }
        }
        else {
            rs = terbilang(nilai.toString());
        }
        
        return rs;
    }
    
    public static String IntToStrFixed(int minLen, int value) {
        String tmpString = String.valueOf(value);
        for (int i=1; 1<minLen - tmpString.length(); i++) {
            tmpString = "0"+tmpString;
        }
        return tmpString; 
    }
     
    
    public static String captionPeriode(Date date1, Date date2){
        String hasil;
  
        hasil = "Periode Global";
        if ((date1 != null) && (date2 !=null)){
            hasil = "Periode "+formatDate(date1) + " s/d "+formatDate(date2);
        }
        else if ((date1 != null) && (date2 ==null)) {        
            hasil = "Per Tanggal "+ formatDate(date1);
        }
        /*if op1 = soEquals then
          hasil := 'Per Tanggal '+ formatDate(date1)
        else if (op1 = soGreaterThanEqualsTo) or (op1 = soGreaterThan) then
          hasil := 'Periode Dari '+ formatDate(date1)+' Sampai Sekarang'
        else if (op1 = soLessThanEqualsTo) or (op1=soLessThan) then
          hasil := 'Periode Awal s/d '+ formatDate(date1);
          * 
          */
     
        return hasil;
     }
     
    public static java.util.Date stringToDate (String value) {
        
        try {
            return new SimpleDateFormat("dd/MM/yyyy").parse(value);
        } catch (ParseException ex) {
            Logger.getLogger(StringUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
    
    public static java.util.Date stringEditorToDate (Object value) {
        Date returnDate = null;
        String newDate = ((String) value).replace(" ", "-");

        try {//coba format I
            returnDate = new SimpleDateFormat(Constants.DATE_EDITOR_FORMAT1).parse(newDate);
        } catch (ParseException ex) {
            try {//coba format II
                returnDate = new SimpleDateFormat(Constants.DATE_EDITOR_FORMAT2).parse(newDate);
            } catch (ParseException ex2) {
                try {//coba format III
                    returnDate = new SimpleDateFormat(Constants.DATE_EDITOR_FORMAT3).parse(newDate);
                } catch (ParseException ex3) {
                    Logger.getLogger(StringUtils.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        return returnDate; 
    }
    
     public static java.util.Date truncDate (java.util.Date value) {
        Date returnDate = value;
        String now = new SimpleDateFormat("dd/MM/yyyy").format(value);
        try {
            returnDate = new SimpleDateFormat("dd/MM/yyyy").parse(now);
        } catch (ParseException ex) {}
        return returnDate; 
    }
     
    public static String getFilter(Map<NameValueList, Object> filter) {
        /*
         * nameValueList.key = kriteria field, misal item.nama
         * nameValueList.value = operator misal =, like, etc
         */
        String filterOut="";
        
        for (Map.Entry<NameValueList, Object> e : filter.entrySet()) {
             NameValueList nameValueList = (NameValueList) e.getKey();
             
             if(Constants.OPERATOR_CUSTOM.equals(nameValueList.getValue())) {
                 filterOut += (filterOut.length()>0 ? " and " : " where ") +e.getValue();
             
             }else if(Constants.OPERATOR_ORDERBY.equals(nameValueList.getValue())) {
             
             }else if (e.getValue() != null && e.getValue() instanceof String) {
                 filterOut += (filterOut.length()>0 ? " and " : " where ") + " lower("+nameValueList.getKey()+") "+ 
                         nameValueList.getValue() + " lower("+StringUtils.fmtSQLString((String)e.getValue())+") ";
             
             }else if (e.getValue() != null && e.getValue() instanceof Date) {
                 filterOut += (filterOut.length()>0 ? " and " : " where ") + nameValueList.getKey()+ 
                         nameValueList.getValue() + StringUtils.formatSqlDate((Date)e.getValue());
                 
             } else {
                 filterOut += (filterOut.length()>0 ? " and " : " where ") + nameValueList.getKey() +" "+ nameValueList.getValue() +" "+
                     (e.getValue() != null ? e.getValue() : "");
             }
        }
        
        //te ngurut uy, kuduna order pang handapna
        for (Map.Entry<NameValueList, Object> e : filter.entrySet()) {
             NameValueList nameValueList = (NameValueList) e.getKey();
             if(Constants.OPERATOR_ORDERBY.equals(nameValueList.getValue())) {
                 filterOut += " order by "+e.getValue();
             }
        }
         
        return filterOut;
    }
    
    
    public static void replaceFilterValue(Map<NameValueList, Object> filter, String toReplace, Object replaceWith) {
        for (Map.Entry<NameValueList, Object> e : filter.entrySet()) {
             NameValueList nameValueList = (NameValueList) e.getKey();
             if (toReplace.equals(nameValueList.getKey())) {
                 e.setValue(replaceWith);
                 return;
             }
        }
    }
     
    public static void deleteFilterValue(Map<NameValueList, Object> filter, String toReplace) {
        
        //params.put(new NameValueList("item.nama", Constants.OPERATOR_LIKE), "%"+txtNama.getText()+"%"); }

        //filter.rd
//        for (Map.Entry<NameValueList, Object> e : filter.entrySet()) {
//             NameValueList nameValueList = (NameValueList) e.getKey();
//             if (toReplace.equals(nameValueList.getKey())) {
//            //     e.setValue(replaceWith);
//                 return;
//             }
//        }
    }
}
